"""
事件处理组件
"""

import tkinter as tk
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ..main_window import MainWindow


class EventHandlerMixin:
    """事件处理 Mixin 类"""
    
    def on_canvas_click(self: 'MainWindow', event):
        """Canvas 左键点击事件"""
        if self.image is None or not self.sam_model.is_loaded():
            return
        
        mode = self.mode_var.get()
        
        if mode == "point":
            # 单点选择
            img_x, img_y = self.canvas_to_image_coords(event.x, event.y)
            
            h, w = self.image.shape[:2]
            if 0 <= img_x < w and 0 <= img_y < h:
                self.selected_points.append([img_x, img_y])
                self.selected_labels.append(1)  # 前景
                
                # 绘制点（景深模式用青色，普通模式用绿色）
                if self.use_depth_input:
                    color = "cyan"
                else:
                    color = self.config.get('ui.markers.foreground', 'green')
                
                radius = self.config.get('ui.markers.marker_radius', 5)
                width = self.config.get('ui.markers.marker_width', 2)
                
                self.original_canvas.create_oval(
                    event.x-radius, event.y-radius,
                    event.x+radius, event.y+radius,
                    fill=color, outline="white", width=width, tags="selection"
                )
                
                mode_info = "景深模式" if self.use_depth_input else "单点模式"
                self.logger.debug(f"{mode_info}：添加前景点: ({img_x}, {img_y})")
                self.update_status(f"已选择 {len(self.selected_points)} 个点")
                
                # 执行分割
                self.segment_interactive()
                
        elif mode == "box":
            # 框选模式 - 开始绘制
            self.drawing_box = True
            self.box_start = (event.x, event.y)
    
    def on_right_click(self: 'MainWindow', event):
        """Canvas 右键点击事件（添加负点）"""
        if self.image is None or not self.sam_model.is_loaded():
            return
        
        mode = self.mode_var.get()
        
        if mode == "point":
            # 添加背景点
            img_x, img_y = self.canvas_to_image_coords(event.x, event.y)
            
            h, w = self.image.shape[:2]
            if 0 <= img_x < w and 0 <= img_y < h:
                self.selected_points.append([img_x, img_y])
                self.selected_labels.append(0)  # 背景
                
                # 绘制红色点
                color = self.config.get('ui.markers.background', 'red')
                radius = self.config.get('ui.markers.marker_radius', 5)
                width = self.config.get('ui.markers.marker_width', 2)
                
                self.original_canvas.create_oval(
                    event.x-radius, event.y-radius,
                    event.x+radius, event.y+radius,
                    fill=color, outline="white", width=width, tags="selection"
                )
                
                self.logger.debug(f"添加背景点: ({img_x}, {img_y})")
                self.update_status(f"已选择 {len(self.selected_points)} 个点")
                
                # 重新执行分割
                self.segment_interactive()
    
    def on_canvas_drag(self: 'MainWindow', event):
        """Canvas 拖动事件"""
        mode = self.mode_var.get()
        
        if mode == "box" and self.drawing_box and self.box_start:
            # 删除之前的框
            self.original_canvas.delete("tempbox")
            
            # 绘制新的框
            self.original_canvas.create_rectangle(
                self.box_start[0], self.box_start[1],
                event.x, event.y,
                outline="blue", width=2, tags="tempbox"
            )
    
    def on_canvas_release(self: 'MainWindow', event):
        """Canvas 释放事件"""
        mode = self.mode_var.get()
        
        if mode == "box" and self.drawing_box:
            self.drawing_box = False
            
            if self.box_start:
                # 转换为图片坐标
                x1, y1 = self.canvas_to_image_coords(self.box_start[0], self.box_start[1])
                x2, y2 = self.canvas_to_image_coords(event.x, event.y)
                
                # 确保坐标顺序正确
                x1, x2 = min(x1, x2), max(x1, x2)
                y1, y2 = min(y1, y2), max(y1, y2)
                
                self.selected_box = [x1, y1, x2, y2]
                
                # 删除临时框，绘制最终框
                self.original_canvas.delete("tempbox")
                # 景深模式用青色，普通模式用绿色
                if self.use_depth_input:
                    color = "cyan"
                else:
                    color = self.config.get('ui.markers.box', 'green')
                
                self.original_canvas.create_rectangle(
                    self.box_start[0], self.box_start[1],
                    event.x, event.y,
                    outline=color, width=3, tags="selection"
                )
                
                mode_info = "景深模式" if self.use_depth_input else "框选模式"
                self.logger.debug(f"{mode_info}：选择框: {self.selected_box}")
                self.update_status(f"已选择框: ({x1},{y1}) 到 ({x2},{y2})")
                
                # 执行分割
                self.segment_interactive()
                
                self.box_start = None
    
    def _setup_shortcuts(self: 'MainWindow'):
        """设置快捷键"""
        # Ctrl+Z 撤销
        self.root.bind('<Control-z>', lambda e: self.undo())
        # Ctrl+Y 重做
        self.root.bind('<Control-y>', lambda e: self.redo())
        # Ctrl+Shift+Z 重做（另一种常见快捷键）
        self.root.bind('<Control-Shift-z>', lambda e: self.redo())
        # Ctrl+Shift+Z 重做（大写）
        self.root.bind('<Control-Shift-Z>', lambda e: self.redo())
        
        self.logger.info("快捷键已设置：Ctrl+Z撤销, Ctrl+Y重做")

